<template>
	<view>
		<!-- 头部 -->
		<navber id="head-navber" navbarBg="transparent" :navbarData="navbarData"></navber>
		<image :src="imgUrl + '/imgs/icon/navbar_bg2.png'" mode="widthFix" class="login-img"></image>
		<view class="login">
			<view class="login-form">
				<!-- <view class="form-tit">
					<text :class="['txt',(login_type==='sms')?'active':'']" @tap="onLoginTypeChange('sms')">手机登录</text>
					<text :class="['txt',(login_type==='password')?'active':'']"
						@tap="onLoginTypeChange('password')">密码登录</text>
				</view> -->

				<u-form :model="formSms" ref="uFormSms" label-width="100" :errorType="['toast']"
					v-if="login_type==='sms'">
					<u-form-item label="+86" prop="phone" class="form-item-input form-item-phone"
						:class="phoneActive?'form-item-active':''">
						<!-- <u-icon name="arrow-right" color="#606060"></u-icon> -->
						<u-input v-model="formSms.phone" placeholder="请输入您的手机号" maxlength="11" type="number"
							:clearable="false" @focus="onInputFocus('phone')" @blur="onInputBlur('phone')" />
						<view :class="['btn',btnSmsDisabled?'btn-disabled':'']" @tap="getCode">{{codeTips}}</view>
					</u-form-item>
					<u-form-item label="验证码" prop="sms_code" class="form-item-input form-item-sms"
						:class="smsActive?'form-item-active':''">
						<u-input v-model="formSms.sms_code" placeholder="请输入短信验证码" maxlength="6" :clearable="false"
							@focus="onInputFocus('sms')" @blur="onInputBlur('sms')" />
					</u-form-item>
				</u-form>

				<u-form :model="formPwd" ref="uFormPwd" label-width="100" :errorType="['toast']" v-else>
					<u-form-item label="手机" prop="phone" class="form-item-input form-item-phone">
						<u-input v-model="formPwd.phone" placeholder="请输入您的手机号" maxlength="11" type="number"
							:clearable="false" @focus="onInputFocus('phone')" @blur="onInputBlur('phone')" />
					</u-form-item>
					<u-form-item label="密码" prop="password" class="form-item-input from-item-password">
						<u-input v-model="formPwd.password" placeholder="请输入登录密码" type="password" :clearable="false" />
					</u-form-item>
				</u-form>
			</view>

			<view class="protocol">
				<view class="login-protocol-selected" @tap="onSelect">
					<image :src="imgUrl + '/imgs/login/' + (protocol ? '' : 'not_') + 'select.png'"></image>
				</view>
				<view class="protocol-text">
					同意
					<span @tap.native="protocolOpen">《{{ protocol_name }}》</span>
				</view>
			</view>

			<view class="login-btn" :class="protocol?'login-btn-active':''" @tap="onGetUser">登录</view>

			<!-- <u-verification-code :keep-running="true" unique-key="sms-login" :seconds="smsCount" ref="uCode"
			@change="onCodeChange"></u-verification-code> -->
			<u-code :keep-running="true" :seconds="smsCount" ref="uCode" @change="onCodeChange"></u-code>
			<u-popup :show="protocolShow" mode="center" @close="protocolClose" @open="protocolOpen">
				<view>
					<view class="ear">
						<view class="ear-title">{{ protocolTitle }}</view>
						<view class="ear-time">{{ protocolTime }}</view>
						<rich-text class="ear-content" :nodes="protocolContent"></rich-text>
						<view class="protocol-btn" @tap="protocolClose">
							<u-button type="primary" text="已阅读"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	import navber from '@/components/navber/index';
	// pages/login/index.js
	const Api = require('../../../api/index.js');
	const Config = require('../../../config/index.js');
	const Util = require('@/utils/sys-util.js');
	const app = getApp();

	export default {
		components: {
			navber
		},
		data() {
			const self = this
			return {
				navbarData: {
					title: "手机号码登录" //顶部标题
				},
				//导航栏
				imgUrl: Config.imgUrl,
				login_type: 'sms',
				seconds: 10,
				phoneActive: false,
				smsActive: false,
				protocol: false,
				//是否选择协议
				protocol_name: app.globalData.title + '注册隐私条款',
				protocolShow: true,
				protocolTitle: "",
				protocolTime: "",
				protocolContent: "",
				formSms: {
					phone: null,
					sms_code: null,
					top_code: ""
				},
				formPwd: {
					phone: null,
					password: null
				},
				user_name: "",
				head_img: "",
				rulesSms: {
					phone: [{
							required: true,
							message: '请输入您的手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value)
							},
							message: '手机号格式不正确',
							trigger: ['change', 'blur']
						}
					],
					sms_code: [{
							validator: (rule, value, callback) => {
								if (isEmpty(value)) {
									callback(new Error('请输入短信验证码'))
								} else {
									callback()
								}
							}
						},
						{
							type: 'number',
							message: '验证码只能为数字',
							trigger: ['change', 'blur']
						},
						{
							min: 6,
							max: 6,
							message: '验证码为6位数字',
							trigger: ['change', 'blur']
						}
					]
				},
				rulesPwd: {
					phone: [{
							required: true,
							message: '请输入您的手机号',
							trigger: ['change', 'blur'],
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.mobile(value)
							},
							message: '手机号格式不正确',
							trigger: ['change', 'blur']
						}
					],
					password: [{
						required: true,
						message: '请输入登录密码',
						trigger: ['change', 'blur'],
					}]
				},
				smsCount: 60,
				codeTips: ''
			}
		},
		computed: {
			btnSmsDisabled() {
				return !(this.$u.test.mobile(this.formSms.phone) && this.$refs.uCode.canGetCode)
			}
		},
		methods: {
			protocolClose() {
				this.protocolShow = false;
				this.protocol = true;
			},
			protocolOpen() {
				this.protocolShow = true;
			},
			onSelect(e, _dataset) {

				if (!e.currentTarget) {
					if (_dataSet.tagId) {
						e.currentTarget = {
							id: _dataSet.tagId
						};
					} else {
						e.currentTarget = {
							dataset: _dataSet
						};
					}
				}

				this.setData({
					protocol: !this.protocol
				});
			},
			getCode() {
				if (this.$u.test.mobile(this.formSms.phone)) {
					if (this.$refs.uCode.canGetCode) {
						uni.showLoading({
							title: '正在获取验证码',
							mask: true
						})
						var json = {
							phone: this.formSms.phone,
						};
						Api.getCode(json).then((res) => {
							if (res.code === 1) {
								uni.hideLoading()
								uni.showToast({
									title: '验证码已发送',
									icon: 'success',
									duration: 3000
								})
								this.$refs.uCode.start()
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none',
									duration: 3000
								})
							}
						})
					} else {
						uni.showToast({
							title: '倒计时结束后再发送',
							icon: 'none',
							duration: 3000
						})
					}
				} else {
					uni.showToast({
						title: '请填写正确的手机号',
						icon: 'none',
						duration: 3000
					})
				}
			},

			onCodeChange(text) {
				this.codeTips = text
			},

			onLoginTypeChange(type) {
				this.login_type = type
				if (type === 'sms') {
					this.$nextTick(function() {
						this.$refs.uFormSms.setRules(this.rulesSms)
					})
				} else {
					this.$nextTick(function() {
						this.$refs.uFormPwd.setRules(this.rulesPwd)
					})
				}
			},

			onInputFocus(e) {
				if (e == 'phone') {
					this.phoneActive = true;
				}
				if (e == 'sms') {
					this.smsActive = true;
				}
			},

			onInputBlur(e) {
				if (e == 'phone') {
					this.phoneActive = false;
				}
				if (e == 'sms') {
					this.smsActive = false;
				}
			},
			onGetUser() {
				uni.getUserProfile({
					desc: '用于完善用户信息',
					// 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						// console.log(res);
						this.user_name = res.userInfo.nickName;
						this.head_img = res.userInfo.avatarUrl;
						this.onSubmit();
					}
				});
			},
			onSubmit() {
				if (this.login_type === 'sms') {
					if (this.protocol == false) {
						uni.showToast({
							title: '请先阅读协议',
							icon: 'none',
							duration: 3000
						})
						return;
					}
					var json = {
						phone: this.formSms.phone,
						code: this.formSms.sms_code,
						top_code: this.formSms.top_code,
						name: this.user_name,
						head_img: this.head_img
					};
					// console.log(json);
					Api.loginPhone(json).then((res) => {
						if (res.code == 1) {
							uni.setStorageSync('access_token', res.data.token);
							uni.setStorageSync('up_cat_new_list', 'up'); //返回上一页
							uni.setStorageSync('superior_top', 'login');
							uni.navigateBack({
								delta: 1
							});
						}
					});
					// console.log(this.protocol);
					// this.$refs.uFormSms.validate(valid => {
					// 	console.log(valid);
					// 	if (valid) {
					// 		console.log(this.formSms);

					// 	}
					// })
				} else {
					// this.$refs.uFormPwd.validate(valid => {
					// 	if (valid) {
					// 		let form = {
					// 			...this.formPwd
					// 		}
					// 		form.login_type = 'password'
					// 		form.password = Util.AesEncrypt(form.password)
					// 		this.login(form).then(res => {
					// 			if (res.code === 1) {
					// 				uni.reLaunch({
					// 					url: '/pages/index/index'
					// 				})
					// 			}
					// 		})
					// 	}
					// })
				}
			}
		},
		onReady() {
			// console.log(this.$refs.uFormSms);
			this.$refs.uFormSms.setRules(this.rulesSms);
			var json = {
				type: 1
			};
			Api.getProtocol(json).then((res) => {
				if (res.code == 1) {
					this.protocolTitle = res.data.title;
					this.protocolTime = res.data.update_time;
					this.protocolContent = res.data.content;
				}
			});
			this.formSms.top_code = uni.getStorageSync('top_code');
			uni.getUserProfile({
				desc: '用于完善会员资料',
				// 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
				success: (res) => {
					console.log(res);
				}
			});
		}
	}
</script>

<style lang="scss">
	page {
		background: #f0f2f5;
	}

	.ear {
		width: 90%;
		padding: 60rpx 5%;
		height: 500px;
		overflow-y: auto;
	}

	.protocol-btn {
		margin-top: 50rpx;
		width: 100%;
		text-align: center;
	}

	/* 注册协议 */
	.login-protocol-selected {
		width: 40rpx;
		height: 40rpx;
		line-height: 1;
	}

	.login-protocol-selected>image {
		width: 100%;
		height: 100%;
	}

	.protocol {
		// position: absolute;
		// bottom: 200rpx;
		margin-top: 30rpx;
		width: 100%;
		text-align: center;
		font-size: 28rpx;
	}

	.protocol>view {
		height: 40rpx;
		line-height: 1;
		display: inline-block;
	}

	.protocol-text {
		position: relative;
		top: -10rpx;
		left: 17rpx;
		color: #9d9d9d;
		border-bottom: 2rpx solid #5099ff;
	}

	.protocol-text>span {
		color: #5099ff;
	}

	.protocol-tip {
		position: relative;
		top: 150rpx;
		text-align: center;
		font-size: 26rpx;
		color: #9d9d9d;
	}

	.login-img {
		width: 750rpx;
		/* background: transparent; */
		position: absolute;
		top: 0;
		left: 0;
	}

	.form-item-active {
		background: #EBF8E6;
	}
</style>

<style lang="scss" scoped>
	.login {
		padding: calc(60rpx + var(--status-bar-height)) 60rpx 60rpx 60rpx;

		.login-bg {
			display: flex;
			justify-content: center;
		}

		.login-form {
			margin-top: 260rpx;

			.form-tit {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 40rpx;
				border-bottom: 2rpx solid #5EC56B;

				.txt {
					display: flex;
					justify-content: center;
					align-items: center;
					width: 100%;
					height: 80rpx;
					color: #606060;
					font-weight: bold;

					&.active {
						background: #5EC56B;
						color: #FFFFFF;
						border-radius: 16rpx 16rpx 0 0;
					}
				}
			}

			::v-deep .u-form {
				.u-form-item {
					&.form-item-input {
						padding-left: 16rpx;
						padding-right: 16rpx;
						border: 2rpx solid #EDEDED;
						border-radius: 16rpx;

						.u-form-item--left {
							color: #606060;
						}

						input {
							font-weight: bold;
							color: #124444;
						}

						.uni-input-placeholder {
							font-weight: normal;
							color: #D2D2D2;
						}
					}

					&.form-item-phone {
						.u-form-item--left {
							width: 35px !important;
							flex: 0 0 35px !important;
						}

						.u-input__input {
							margin-left: 24rpx;
						}

						.btn {
							position: relative;
							height: 76rpx;
							background: #5EC56B;
							color: #FFFFFF;
							text-align: center;
							line-height: 76rpx;
							font-weight: bold;
							border-radius: 12rpx;
							padding: 0 35rpx;

							&.btn-disabled {
								background: #EDEDED;
								color: #B8B8B8;
							}
						}
					}

					&.form-item-sms {
						margin-top: 40rpx;

						.u-input__input {
							margin-left: 16rpx;
						}
					}

					&.from-item-password {
						margin-top: 40rpx;
					}
				}
			}
		}

		.login-btn {
			height: 90rpx;
			line-height: 90rpx;
			background: #c3c3c3;
			color: #999999;
			text-align: center;
			font-size: 36rpx;
			font-weight: bold;
			border-radius: 54rpx;
			margin-top: 80rpx;
		}

		.login-btn-active {

			background: #5EC56B;
			color: #FFFFFF;
		}
	}
</style>
